import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.knowledge.video.mapper.VideoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
@Component
public class VideoDataSyncTask {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private VideoMapper videoMapper;

    // 每 5 分钟同步一次（可调整）
    @Scheduled(cron = "0 0/5 * * * ?")
    public void syncLikeAndCollectData() {
        syncLikeData();
        syncCollectData();
    }

    private void syncLikeData() {
        Set<String> likeKeys = (Set<String>) redisCache.keys("video:like:*");
        for (String key : likeKeys) {
            String videoIdStr = key.replace("video:like:", "");
            Long videoId = Long.valueOf(videoIdStr);
            Integer likeCount = redisCache.getCacheObject(key);
            if (likeCount != null && likeCount > 0) {
                videoMapper.updateLikeCount(videoId, likeCount);
                redisCache.deleteObject(key); // 清空缓存计数，避免重复累加
            }
        }
    }

    private void syncCollectData() {
        Set<String> collectKeys = (Set<String>) redisCache.keys("video:collect:*");
        for (String key : collectKeys) {
            String videoIdStr = key.replace("video:collect:", "");
            Long videoId = Long.valueOf(videoIdStr);
            Integer collectCount = redisCache.getCacheObject(key);
            if (collectCount != null && collectCount > 0) {
                videoMapper.updateCollectCount(videoId, collectCount);
                redisCache.deleteObject(key);
            }
        }
    }
}